//
//  CLLiveDataModel.m
//  chanlin
//
//  Created by Ryan on 15/6/5.
//  Copyright (c) 2015年 chanlin. All rights reserved.
//

#import "CLLiveDataModel.h"
#import "ChangyanSDK.h"
#import "SgrGCD.h"
#import "IFCoreDataManager.h"
#import "CLLive.h"
#import "CLComentDataModel.h"
#import "CLLiveCell.h"

@implementation CLLiveDataModel

- (instancetype)initWithId:(NSString *)liveId{
    self=[super init];
    if(self){
        self.liveId=liveId;
        self.first=YES;
    }
    return self;
}

- (void)getMessage:(NSString *)liveId :(void (^)(BOOL success,id responseObj,NSError *message,NSMutableDictionary *param) )block2{
    NSString *url=[NSString stringWithFormat:[self urlWithCategory:@"slider"],liveId];
    [self getWithUrl:url
               param:nil
           dataBlock:^(BOOL success, id responseObj, NSError *message, NSMutableDictionary *param) {
               
           } uiBlock:^(BOOL success, id responseObj, NSError *message, NSMutableDictionary *param) {
               if(block2)block2(success,responseObj,message,param);
           }];
}


- (void)reflashNextPage:(NSInteger )page :(CLLive *)last :(void (^)(BOOL success,id responseObj,NSString *message) )block{
    if(_isStrNULL(self.topciId) || _isStrNULL(self.liveId)) return;
    __weak typeof(self) me=self;
    
    [ChangyanSDK getTopicComments:self.topciId
                         pageSize:@"20"
                           pageNo:[NSString stringWithFormat:@"%d",page]
                    completeBlock:^(CYStatusCode statusCode, NSString *responseStr) {
                        if(statusCode==CYSuccess){
                            [[IFCoreDataManager sharedInstance] performBlock:^(NSManagedObjectContext *moc) {
                                
                        
                                
                                
                                [me doEntity:moc :responseStr :YES:last?last.order:0];
                                [[IFCoreDataManager sharedInstance] saveContext:moc ToPersistentStore:nil];
                                if(block){
                                    sgrSafeMainThread(^{
                                        block(YES,nil,@"");
                                    });
                                    
                                }
                                
                                
                            }];
                            
                        }else{
                            if(block){
                                sgrSafeMainThread(^{
                                    block(NO,nil,@"");
                                });
                                
                            }
                            
                        }
                    }];


}


- (void)reflashData:(void (^)(BOOL success,id responseObj,NSString *message) )block{
    
    if(_isStrNULL(self.liveId)) return;
    __weak typeof(self) me=self;
    if(_isStrNULL(self.topciId)){
        
       
        
        [ChangyanSDK loadTopic:@""
                    topicTitle:self.titlestr
                 topicSourceID:self.liveId
                      pageSize:@"20"
                       hotSize:@"0"
                 completeBlock:^(CYStatusCode statusCode, NSString *responseStr) {
                     if(statusCode==CYSuccess){
                         
                         NSString *liveId=me.liveId;
                         
                         [[IFCoreDataManager sharedInstance] performBlock:^(NSManagedObjectContext *moc) {
                             
                             
                             NSArray *items=[CLLive fetchAllWithPredict:
                                             [NSPredicate predicateWithFormat:@"room=%@ and liveId==%@",@(me.room),liveId]
                                                                 withMOC:moc];
                             if(items){
                                for(CLLive *item in items){
                                    [moc deleteObject:item];
                                    }
                                }
                             
                             [me doEntity:moc :responseStr :NO:0];
                             
                             [[IFCoreDataManager sharedInstance] saveContext:moc ToPersistentStore:nil];
                             
                             if(block){
                                 sgrSafeMainThread(^{
                                     block(YES,nil,@"");
                                 });

                             }
                        }];
                         
                     }else{
                         if(block){
                             sgrSafeMainThread(^{
                                 block(NO,nil,@"");
                             });
                             
                         }

                     }
                 }];
        

    }else{
        [ChangyanSDK getTopicComments:self.topciId
                             pageSize:@"20"
                               pageNo:[NSString stringWithFormat:@"%d",1]
                        completeBlock:^(CYStatusCode statusCode, NSString *responseStr) {
                            if(statusCode==CYSuccess){
                               [[IFCoreDataManager sharedInstance] performBlock:^(NSManagedObjectContext *moc) {
                                   
                                   NSArray *items=[CLLive fetchAllWithPredict:
                                                   [NSPredicate predicateWithFormat:@"room=%@ and liveId==%@",@(me.room),self.liveId]
                                                                      withMOC:moc];
                                   if(items){
                                       for(CLLive *item in items){
                                           [moc deleteObject:item];
                                       }
                                   }

                                   
                                   [me doEntity:moc :responseStr :YES:0];
                                   [[IFCoreDataManager sharedInstance] saveContext:moc ToPersistentStore:nil];
                                   if(block){
                                       sgrSafeMainThread(^{
                                           block(YES,nil,@"");
                                       });
                                       
                                   }

                                   
                               }];
                            
                            }else{
                                if(block){
                                    sgrSafeMainThread(^{
                                        block(NO,nil,@"");
                                    });
                                    
                                }

                            }
                        }];

    }
}






- (void)doEntity:(NSManagedObjectContext *)moc :(NSString *)responseStr :(BOOL)noUpdate :(NSInteger )order{
    NSDictionary *dic=(NSDictionary *)[[CLGloble sharedInstance] jsonFromString:responseStr];
    
    if(_isStrNULL(self.topciId)) self.topciId=[dic sgrFGetStringForKey:@"topic_id"];
    NSArray *comts=[dic sgrGetArrayForKey:@"comments"];
    int i=0;
    NSInteger last=order+1;
    for(NSDictionary *dic in comts){
        
        if(noUpdate){
            NSString *cid=[dic sgrFGetStringForKey:@"comment_id"];
            CLLive *live=(CLLive *)[CLLive fetchWithPredict:
                          [NSPredicate predicateWithFormat:@"room=%@ and liveId=%@ and cmtId=%@",@(self.room),self.liveId,cid]
                                          withMOC:moc];
            
            if(live){
                live.order=(i+last);
                continue;
            }
        }
        
        CLLive *live=[CLLive managerObjWithMoc:moc];
        live.liveId=self.liveId;
        NSString *content=[dic sgrGetStringForKey:@"content"];
        NSArray *strarr=[content componentsSeparatedByString:@"#^"];
        if([strarr count]>1){
            live.title=[strarr sgrGetStringForIndex:0];
            live.content=[strarr sgrGetStringForIndex:1];
        }else{
            live.content=[strarr sgrGetStringForIndex:0];
        }
        NSArray *replyarr=[live.content componentsSeparatedByString:@"#$"];
        if(replyarr.count>1){
            live.content=[replyarr sgrGetStringForIndex:0];
            NSArray *replyArr=[[replyarr sgrGetStringForIndex:1] componentsSeparatedByString:@"#-"];
            live.replyname=[replyArr sgrGetStringForIndex:0];
            live.replyroom=[replyArr sgrGetStringForIndex:1];
            live.replycontent=[replyArr sgrGetStringForIndex:2];
        }
        
        
        NSString *img=[[[dic sgrGetArrayForKey:@"attachments"]
                        sgrGetDictionaryForIndex:0]
                       sgrGetStringForKey:@"url"];
        live.img=img;
        live.nickName=[[dic sgrGetDictionaryForKey:@"passport"] sgrGetStringForKey:@"nickname"];
        live.usrImg=[[dic sgrGetDictionaryForKey:@"passport"] sgrGetStringForKey:@"img_url"];
        live.order=(i+last);
        live.support=[dic sgrGetIntForKey:@"support_count"];
        live.room=self.room;
        live.cmtId=[dic sgrFGetStringForKey:@"comment_id"];
        live.time=[[dic sgrGetNumberForKey:@"create_time"] longLongValue];
        live.videoUrl=[[[dic sgrGetArrayForKey:@"attachments"]
                        sgrGetDictionaryForIndex:1]
                       sgrGetStringForKey:@"url"];
        
        CGFloat width=GlobleWidth-2*CLLiveCell_mesage_padding-CLLiveCell_mesage_left-CLLiveCell_mesage_right;
        
        CGFloat width2=width-4*CLLiveCell_reply_marge;
        if(_isStrNotNull(live.title)){
        CGRect rect=[live.title boundingRectWithSize:CGSizeMake(width, 3000)
                                             options:NSStringDrawingUsesLineFragmentOrigin
                                          attributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:CLLiveCell_titleFont]}
                                             context:nil];
            live.titleHeight=rect.size.height;
            
        }else{
            live.titleHeight=0;
        }
        
        if(_isStrNotNull(live.content)){
            CGRect rect=[live.content boundingRectWithSize:CGSizeMake(width-3.f, 3000)
                                                 options:NSStringDrawingUsesLineFragmentOrigin
                                              attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:CLLiveCell_contentFont]}
                                                 context:nil];
          
            
            live.contentHeight=rect.size.height+4.f;
            
        }else{
            live.contentHeight=0;
        
        }
        
        if(_isStrNotNull(live.replycontent)){
            CGRect rect=[live.replycontent boundingRectWithSize:CGSizeMake(width2-10.f, 3000)
                                                   options:NSStringDrawingUsesLineFragmentOrigin
                                                attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:CLLiveCell_contentFont]}
                                                   context:nil];
            live.replycHeight=rect.size.height+4.f;

        }else{
            live.replycHeight=0;
        }
        
        
        
        
        
        i++;
    }

}

@end
